package cn.test.my.excel.listdata;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * excel导出
 *
 * @author summit
 * @since 2021/7/8 21:22
 */
public class ExcelEasyExport {


	/**
	 * 生成excel文件
	 */
	public static void startExport(OutputStream out, List<String> headList, List<List<String>> dataList) {
		startExport(out, headList, dataList, "sheet-0");
	}

	/**
	 * 生成excel文件
	 */
	public static void startExport(OutputStream out, List<String> headList, List<List<String>> dataList, String sheetName) {
		Workbook workbook = new HSSFWorkbook();
		Sheet sheet = workbook.createSheet(sheetName);
		CellStyle style = getCellStyle(workbook);

		int index = 0;
		Row headRow = sheet.createRow(index);
		int headNum = 0;
		for (String h : headList) {
			Cell cell = headRow.createCell(headNum++);
			cell.setCellValue(h);
			cell.setCellStyle(style);
		}
		for (List<String> value : dataList) {
			index++;
			Row row = sheet.createRow(index);
			int num = 0;
			for (String str : value) {
				Cell cell = row.createCell(num++);
				cell.setCellValue(str);

				cell.setCellStyle(style);
			}
		}
		try {
			workbook.write(out);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			if (out != null) {
				try {
					out.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}

			}
		}

	}

	/**
	 * 生成简单的样式
	 * @param workbook 工作簿
	 * @return cell样式
	 */
	private static CellStyle getCellStyle(Workbook workbook) {
		// 生成一个样式
		CellStyle style = workbook.createCellStyle();

		// 设置这些样式
		style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		style.setBorderBottom(BorderStyle.THIN);
		style.setBorderLeft(BorderStyle.THIN);
		style.setBorderRight(BorderStyle.THIN);
		style.setBorderTop(BorderStyle.THIN);
		style.setAlignment(HorizontalAlignment.CENTER);
		// 生成一个字体
		Font font = workbook.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBold(false);
		// 把字体应用到当前的样式
		style.setFont(font);
		return style;
	}

}
